const { Server } = require("socket.io");

const io = new Server({ cors: true });

const { port, game } = require("./server/config.json");
const db_handler = require('../服务端/server/db_handler.js');
const Handler = require("../服务端/server/handler.js");

const battlefield = new Map();

io.on("connection", (socket) => {

    //创建
    socket.on("create", (data, callback) => {
        const battle = new Battle(data);
        battlefield.set(data.battleId, battle);
        callback();
    })

    //加入
    socket.on("join", (data) => {
        const { battleId, name } = data;
        const battle = battlefield.get(battleId);
        socket.battleId = battleId;
        socket.join(battleId);
        battle.join(name);
    })

    //接受指令
    socket.on("battle input", (data) => {
        const battleId = socket.battleId;
        io.in(battleId).emit("battle player input", data);
    })
})

io.listen(6545, function () {
    console.log(`地图服务已开启,${port.map}端口被监听...`);
})

class Battle {
    constructor(data) {
        const { battleId, member, troopId } = data;
        this._battleId = battleId;
        this._member = member;
        this._troopId = troopId;
        this.setReadyState();
    }

    setReadyState() {
        this._ReadyState = {};
        for (const player of this._member) {
            this._ReadyState[player] = false;
        }
    }

    join(name) {
        this._ReadyState[name] = true;
        for (const player of this._member) {
            if (this._ReadyState[player] === false) return;
        }
        const troopId = this._troopId;
        io.in(this._battleId).emit("battle start", troopId);
    }
}